package util;

import entity.ResponseMessage;
import entity.StatusCode;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * The type Down load file.
 */
public class DownLoadFile {
    private static String rootPath = "D://finally/picture";

    /**
     * Down load file response message.
     *
     * @param response the response
     * @param fileName the file name
     * @return the response message
     */
    public static ResponseMessage downLoadFile(HttpServletResponse response, String fileName) {
        ResponseMessage msg = new ResponseMessage();
        try {
            File file = new File(rootPath + "/" + fileName);
            if (file.exists()) {
                InputStream is = new FileInputStream(file);
                ServletOutputStream os = response.getOutputStream();
                byte[] bytes = new byte[1024];
                int n = 0;
                while ((n = is.read(bytes)) != -1) {
                    os.write(bytes, 0, n);
                }
                msg.setCode(StatusCode.OK);
                msg.setFlag(true);
                is.close();
                os.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(StatusCode.ERROR);
            msg.setFlag(false);
        }
        return msg;
    }
}
